package room_event

import (
	"encoding/json"
	"fmt"
	"github.com/jinzhu/copier"
	global2 "longmen/server/config/global"
	cache2 "longmen/server/internal/rpc/tencentim/cache"
	"longmen/server/internal/rpc/tencentim/chat"
	"longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/utils"
	"longmen/server/internal/services/consumers/publisher"
	"longmen/server/pkg/common/api_models"
	"longmen/server/pkg/common/services"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
)

/*
处理礼物信息，成功群发礼物动画
失败的话给单用户回复失败消息
*/

const (
	GiftPriceTypeDiamond           = iota + 1                   // 鹰钻
	RoomStatsGiftTotalPrice        = "gift_total_price"         // 礼物总价值
	RoomStatsGiftTotalNum          = "gift_total_num"           // 礼物总数
	RoomStatsGiftDiamondTotalPrice = "gift_diamond_total_price" // 鹰钻价值
	RoomStatsGiftDiamondTotalNum   = "gift_diamond_total_num"   // 鹰钻总数
)

type GiftReqStruct struct {
	Anchorid uint32 `json:"anchorid"`
	Giftid   uint32 `json:"giftid"`
	Liveid   uint64 `json:"liveid"`
	Count    uint32 `json:"count"`
	Uid      uint32 `json:"uid"`
}

type GiftHeat struct {
	User    chat.ClientUser //用户信息
	GiftReq GiftReqStruct   //礼物信息
}

func handlingGiftMessage(user *chat.ClientUser, b []byte) (ret *pb.CallbackResp, err error) {
	//检查够不够钱，不够的话给用户单发消息，成功的话返回新余额，礼物信息
	ret = &pb.CallbackResp{}
	giftReq := &api_models.SendGiftReq{}
	errIntern := json.Unmarshal(b, giftReq)

	if errIntern != nil {
		ret.ErrorCode = imsdk.TIM_SEND_GIFT_ERR
		ret.ErrorInfo = errIntern.Error()
		return utils.CallbackFailResp(ret, errIntern.Error()), nil
	}
	giftReq.Anchorid = user.RoomId
	giftReq.Uid = user.UserId
	global2.Log.Infof("6SendGift9:%v", giftReq)
	//fixme  扣款
	giftResp, errIntern := TimSendGift(giftReq)
	if errIntern != nil || giftResp == nil {
		//送礼失败，拒绝
		//return util.CallbackFailResp(ret, errIntern.Error()), errIntern
		sInfo := errIntern.Error()
		ret.ErrorCode = imsdk.TIM_SEND_GIFT_ERR //用特殊的错误代码进行回复
		ret.ErrorInfo = string(sInfo)           //这里带上回复消息
		oRet := utils.CallbackRespWithCode(imsdk.TIM_SEND_GIFT_ERR, ret.ErrorInfo, ret)
		global2.Log.Infof("6oRet9,%v", oRet)
		return oRet, nil
	} else { //发送成功了，现在给用户的消息是放在回调回复里的
		// 发送成功暂时不回复
		sInfo, _ := json.Marshal(giftResp)
		ret.ErrorCode = imsdk.TIM_CODE_OK //为0好像是收不到回复的
		ret.ErrorInfo = string(sInfo)     //这里带上回复消息
	}

	giftInfo, err := cache.GetGiftInfo(giftReq.Giftid)
	//fixme 此业务应该放在后面去执行，暂时未有移步
	giftHeatCalculator(user, giftReq)

	//改装后，，发出消息
	oGiftMsg := messages2.GiftStruct{
		Giftid:         giftReq.Giftid,
		Count:          giftReq.Count,
		Sender:         giftReq.Uid,
		FromClientName: cache.GetUserNickNameById(giftReq.Uid),
		Avatar:         user.Avatar,
		Animation:      giftInfo.Animation,
		GiftName:       giftInfo.Title,
		Hit: int(
			cache.UserGiftHitCounter(giftReq.Uid, giftReq.Giftid)),
		Duration: giftInfo.Duration,
		Level:    user.Level,
	}

	//oNode.Msg = string(bGiftMsg)
	oBalance := &api_models.SendGiftResp{}
	copier.Copy(oBalance, giftResp) //余额copy进去

	resp := &messages2.RoomUserGiftMsg{
		SentMessageStruct: messages2.SentMessageStruct{Type: messages2.GiftMessageType},
		GiftStruct:        oGiftMsg,
	}
	bGiftMsg, _ := json.Marshal(resp)
	cache2.PushGiftReplyMsg(user.UserId, oBalance, string(bGiftMsg)) //把要给用户回复的消息放进缓存
	return utils.CallbackRespWithCode(int(ret.ErrorCode), ret.ErrorInfo, resp), nil

}

func giftHeatCalculator(user *chat.ClientUser, giftReq *api_models.SendGiftReq) {

	var newGiftReq GiftReqStruct
	newGiftReq.Anchorid = uint32(giftReq.Anchorid)
	newGiftReq.Giftid = uint32(giftReq.Giftid)
	newGiftReq.Liveid = uint64(giftReq.Liveid)
	newGiftReq.Count = uint32(giftReq.Count)
	newGiftReq.Uid = uint32(giftReq.Uid)

	giftHeat := &GiftHeat{
		User:    *user,
		GiftReq: newGiftReq,
	}
	//apiCache.PushAny(giftHeat, messages.HeatCalculatorChannel)
	global2.PublisherTxChat.BroadCast(publisher.GiftHeat, giftHeat)

}

// 发送礼物
func TimSendGift(req *api_models.SendGiftReq) (*api_models.SendGiftResp, error) {
	global2.Log.Infof("6SendGift9 sending gift:%+v", req)
	oNode := &messages2.GiftReplyNode{}
	var f_make_msg = func(msg string) string { //传入错误信息，生成一个json数据
		oNode.Msg = msg
		bNode, _ := json.Marshal(oNode)
		return string(bNode)
	}
	var (
		err error
	)
	r := &api_models.SendGiftReq{Giftid: req.Giftid, Anchorid: req.Anchorid, Liveid: req.Liveid, Count: req.Count}
	if r.Count <= 0 {
		r.Count = 1
	}
	user, err := cache.GetUserFullInfo(req.Uid)
	if err != nil {
		return nil, err
	}
	resp, err := services.SendGiftSubtract(r, user.Id)
	oNode.Balance = resp
	if err != nil {
		global2.Log.Error(err)
		return nil, fmt.Errorf(f_make_msg(err.Error()))
	}
	r.Uid = user.Id
	//进入送礼物队列
	//err = cache.PushSendGift(r)
	if err != nil {
		return nil, fmt.Errorf(f_make_msg("系统超时请重试"))
	}
	global2.Log.Debugf("6SendGift9,id:%v,价格:%v,类型:%v,数量:%v", req.Giftid, resp.GiftPrice, resp.PriceType, req.Count)
	//fixme
	giftPrice := resp.GiftPrice / 100
	cache2.NewRoomHeat(req.Anchorid).SetGiftInc(giftPrice, resp.PriceType, req.Count)

	return &api_models.SendGiftResp{Gold: resp.Gold, Diamond: resp.Diamond}, nil
}
